package cn.haocxy.jfm.gui;

import javafx.scene.control.MenuItem;
import cn.haocxy.jfm.file.Clipboard;
import cn.haocxy.jfm.file.Clipboard.Mode;
import cn.haocxy.jfm.file.FilePath;
import cn.haocxy.jfm.func.FileFunc;
import cn.haocxy.jfm.func.GUIFunc;

/**
 * 在一项文件上打开的右键菜单 与之对应的是在已选的多个文件项上打开的右键菜单。
 * 
 * 全局使用惟一一个菜单，单例模式
 * 
 * @author 蔡心宇
 *
 */
class FileItemMenuSingle extends FileItemMenu {

	private final MenuItem open;

	private final MenuItem openInNew;

	private final MenuItem rename;

	private final MenuItem copy;

	private final MenuItem paste;

	private final MenuItem remove;
	
	private final MenuItem cut;
	
	private final MenuItem sep;
	
	public FileItemMenuSingle() {
		super();

		open = add("打开", this::open);

		openInNew = add("新窗口打开", this::openInNewWindow);

		addSep();
		
		rename = add("重命名", this::rename);

		copy = add("复制", this::copy);
		
		cut = add("剪切", this::cut);

		paste = add("粘贴", this::paste);

		sep = addSep();
		
		remove = add("删除", this::remove);
		
		
	}

	@Override
	protected void filt() {

		FilePath path = getItemPath();

		boolean isWin32Part = path.isWin32Part();
		boolean canOpen = path.canOpen();
		boolean isDir = path.isDirectory();
		boolean readable = path.isReadable();
		boolean writable = path.isWritable();

		
		Clipboard cb = Clipboard.get();

		filt(open, item -> canOpen);

		filt(openInNew, item -> isDir && canOpen);

		filt(rename, item -> !isWin32Part && writable);

		filt(copy, item -> readable);

		filt(paste, item -> !cb.isEmpty() && isDir && writable);

		filt(remove, item -> !isWin32Part && writable);
		
		filt(cut, item -> !isWin32Part && writable);
		
		filtSep(sep, item -> !isWin32Part && writable);
		
	}

	private void open() {
		FilePath path = getItemPath();
		if (path.isDirectory()) {
			getFileList().setDir(getItemPath());
		} else {
			path.open();
		}
	}

	private void openInNewWindow() {
		GUIFunc.newJfmWindow(getCurrentWindow(), getItemPath()); 
	}

	private void rename() {
		getIconArea().getFileItemGUI().getNameArea().edit();
	}

	private void copy() {
		Clipboard cb = Clipboard.get();
		cb.setMode(Mode.COPY);
		cb.add(getItemPath());
	}

	private void paste() {
		FileFunc.paste(getItemPath(), null);
	}
	
	private void remove() {
		boolean ok;
		ok = GUIFunc.confirm(getCurrentWindow(), 
				"删除后无法恢复 , 确认删除 '" + getItemPath().getFileName() + "' ?");
		if (ok) {
			FileFunc.remove(getItemPath(), null);
		}
	}
	
	private void cut() {
		Clipboard cb = Clipboard.get();
		cb.setMode(Mode.MOVE);
		cb.add(getItemPath());
	}
}
